package com.sm;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.StandardCharsets;

/**
 * @Author WLZ
 * @date 2022年3月8日14:42:55
 */
@Slf4j
public class SM4Tools {

    /**
     *
     * @param keyh 16进制文本密钥
     * @param ivh 16进制偏移量
     * @param srcData 明文
     * @return 16进制文本密文
     */
    public static String encryptCBC(String keyh,String ivh,String srcData) {
        try {
            byte[] key = Hex.decode(keyh);
            byte[] iv = Hex.decode(ivh);
            byte[] cipherText = null;
            cipherText = SM4Util.encrypt_CBC_Padding(key, iv, srcData.getBytes(StandardCharsets.UTF_8));
            String cipetext = Hex.toHexString(cipherText);
            return cipetext;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("SM4加密失败："+ex.getMessage());
        }
        return null;
    }

    /**
     *
     * @param keyh 16进制文本密钥
     * @param ivh 16进制偏移量
     * @param cipherText 16进制文本密文
     * @return 明文
     */
    public static String decryptCBC(String keyh,String ivh,String cipherText) {
        try {
            byte[] key = Hex.decode(keyh);
            byte[] iv = Hex.decode(ivh);
            byte[] decryptedData = SM4Util.decrypt_CBC_Padding(key, iv, Hex.decode(cipherText));
            return new String(decryptedData);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("SM4解密失败："+ex.getMessage());
        }
        return null;
    }

    /**
     *
     * @param keyh 16进制文本密钥
     * @param srcData 明文
     * @return 16进制密文
     */
    public static String encryptEBC(String keyh,String srcData) {
        try {
            byte[] key = Hex.decode(keyh);
            byte[] cipherText = null;
            cipherText = SM4Util.encrypt_ECB_Padding(key,srcData.getBytes(StandardCharsets.UTF_8));
            String cipetext = Hex.toHexString(cipherText);
            return cipetext;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("SM4加密失败："+ex.getMessage());

        }
        return null;
    }

    /**
     * ECB模式
     * @param keyh 16进制文本密钥
     * @param cipherText 16进制文本密文
     * @return 明文
     */
    public static String decryptEBC(String keyh,String cipherText) {
        try {
            byte[] key = Hex.decode(keyh);
            byte[] decryptedData = SM4Util.decrypt_ECB_Padding(key, Hex.decode(cipherText));
            return new String(decryptedData);
        } catch (Exception ex) {
            log.error("SM4解密失败：", ex);
        }
        return null;
    }

}
